package com.liruo.treasureattic.common.util;

import java.math.BigInteger;

/**
 * @Author:liruo
 * @Date:2023-02-05-22:19:48
 * @Desc
 */
public class BitUtils {

    /**
     * 仅支持正数
     */
    public static String repairBinaryString(String s){
        return repairBinaryString(s, (s.length() + (s.length() - 1)) / Byte.SIZE);
    }
    /**
     * 仅支持正数
     */
    public static String repairBinaryString(String s, int byteLen){
        int bits = byteLen * Byte.SIZE;
        if(s.length() == bits){
            return s;
        }
        int diff = bits - s.length();
        return "0".repeat(diff) + s;
    }

    /**
     *
     * Integer.numberOfLeadingZeros返回从左往右数的第一个1的位置,用总数31-该位置就是反过来从右到左了
     *       0返回32, 负数返回0---第31位是1会返回1
     *       因此他是1-31共31位 如果是第1位那么31-1=30=30-1+1就是从右往左数
     * @param target 可正, 负返回0 0返回-1
     * @return high1表示高位1,返回高位第一个1的位置(二进制位置)
     */
    public static int findHigh1(int target){
        if(target < 0){
            target = - target;
        }
        return 31  - Integer.numberOfLeadingZeros(target);
    }
    public static int findHigh1(long target){
        if(target < 0){
            target = - target;
        }
        return 63  - Long.numberOfLeadingZeros(target);
    }
    public static int findHigh1(BigInteger target){
        return target.bitLength();
    }

    /**
     *
     * @param val 值
     * @param target 按二进制算 从high移到target
     * @param lowerBits  低位的位数
     * @return
     */
    public static long rmToTarget(long val, int target, int lowerBits){
        return val << (target - lowerBits);
    }
    public static long rmToTarget(long val, int leftMax, int space, int lowerBits){
        return val << (leftMax - space - lowerBits);
    }

    public static long stableLongByte(byte b){
        return Byte.toUnsignedLong(b);
    }
    public static int stableIntByte(byte b){
        return Byte.toUnsignedInt(b);
    }
}
